package com.example.demorabbitmq.controller;

import com.example.demorabbitmq.constant.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("/producer")
public class ProducerController {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RabbitTemplate transactionTemplate;

    @RequestMapping("/work")
    public String work() {
        rabbitTemplate.convertAndSend("", Constants.WORK_QUEUE, "hello spring amqp work...");
        return "发送成功";
    }

    @RequestMapping("/fanout")
    public String fanoutProduct() {
        rabbitTemplate.convertAndSend(Constants.FANOUT_EXCHANGE_NAME, "", "hello spring boot: fanout");
        return "发送成功";
    }

    @RequestMapping("/routing")
    public String routingProduct(String routingKey) {
        rabbitTemplate.convertAndSend(Constants.DIRECT_EXCHANGE_NAME, routingKey, "hello spring boot: routing" + routingKey);
        return "发送成功";
    }

    @RequestMapping("/topic")
    public String topicProduct(String routingKey) {
        rabbitTemplate.convertAndSend(Constants.TOPICS_EXCHANGE_NAME, routingKey, "hello spring boot: topic" + routingKey);
        return "发送成功";
    }

    @RequestMapping("/delayed")
    public String delayedProduct() {
        rabbitTemplate.convertAndSend(Constants.DELAYED_EXCHANGE, "delayed", "hello spring boot: delayed" + new Date(), message -> {
            message.getMessageProperties().setDelay(5000);
            return message;
        });
        return "发送成功";
    }


    @RequestMapping("/trans")
    @Transactional
    public String transactionProduct() {
        transactionTemplate.convertAndSend("",Constants.TRANS_QUEUE, "trans test 1...");
        int a = 5/0;//发生异常回滚
        transactionTemplate.convertAndSend("",Constants.TRANS_QUEUE, "trans test 2...");
        return "发送成功";
    }
}
